<?php

namespace App\Console\Commands;

use DOMDocument;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Cloudstudio\Ollama\Facades\Ollama;

class UpdateFetchJobData extends Command
{
    protected $signature   = 'update:job-info {--examtype=default_examtype} {--city=default_city} {--year=default_year} {--month=default_month} ';
    protected $description = 'Individually update each job data record based on the given criteria';
    /** @var  Client */
    protected $client;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        ini_set('memory_limit', -1);

        // 获取传入的参数
        $examtype = $this->option('examtype');
        $city = $this->option('city');
        $year = $this->option('year');
        $month = $this->option('month');
        // $field = $this->option('field');
        // $value = $this->option('value');

        // if (!$field || !$value) {
        //     $this->error('Field and value options are required.');
        //     return;
        // }

        // 构建查询
        $query = DB::table('jobs');


        if ($examtype !== 'default_examtype') {
            $query->where('examtype', $examtype);
        }

        if ($city !== 'default_city') {
            $query->where('city', $city);
        }

        if ($year !== 'default_year') {
            $query->whereYear('pubdate', $year);
        }

        if ($month !== 'default_month') {
            $query->whereMonth('pubdate', $month);
        }
        $query->where('status', 2);
        $updatedCount = 0;
        // 获取符合条件的数据并逐条更新
        $jobs = $query->get();
        foreach ( $jobs as $job ) {
            try {
                // 对单条记录进行处理
                $updateData = [];

                if (! $job->result) {
                    continue;
                }
                // if(!$job->interview_rate){
                //     continue;
                // }
                // $updateData['interview_rate']=$this->swap_ratio_if_needed($job->interview_rate);

                $result = preg_replace('/^```json\s*|\s*```$/m', '', $job->result);

                $jsonResult = json_decode($result, true);

                if (! $jsonResult) {
                    continue;
                }

                // if ($job->bkggzkrs == 0) {
                //     $updateData['bkggzkrs'] = $jsonResult['user_num']?:'未查询到';
                // }
                // if (! $job->bkggkssj || $job->bkggkssj == '另行通知') {
                //     $updateData['bkggkssj'] = $jsonResult['exam_date'] ?: '未查询到';
                // }
                if (! $job->bkggksnr || $job->bkggksnr='见公告' ) {
                    $updateData['bkggksnr'] = $jsonResult['exam_content'] ?: '未查询到';
                }
                // if (! $job->query_time) {
                //     $updateData['query_time'] = $jsonResult['results_query_date'] ?: '未查询到';
                // }
                // if (! $job->bkggmssj) {
                //     $updateData['bkggmssj'] = $jsonResult['interview_date'] ?: '未查询到';
                // }
                // if (! $job->interview_content) {
                //     $updateData['interview_content'] = $jsonResult['interview_content'] ?: '未查询到';
                // }
                // if (! $job->interview_rate) {
                //     $updateData['interview_rate'] = $jsonResult['interview_ratio'] ?: '未查询到';
                // }
                // if($updateData){
                //     $updateData['status']=2;
                // }
                $updateResult = DB::table('jobs')
                                  ->where('id', $job->id)
                                  ->update($updateData);
                if ($updateResult) {
                    $updatedCount++;
                    $this->info("Record with ID {$job->id} has been updated.");
                } else {
                    $this->error("Failed to update record with ID {$job->id}.");
                }
                // sleep(rand(0,2));
            } catch (\Throwable $exception) {
                $this->error("Failed to update record with ID {$job->id}.".$exception->getMessage());
                continue;
            }

        }

        $this->info("Total {$updatedCount} record(s) have been updated.");
    }

    public function swap_ratio_if_needed($ratio) {
        $pattern = '/^(\d+):(\d+)$/';

        if (preg_match($pattern, $ratio, $matches)) {
            $first = (int)$matches[1];
            $second = (int)$matches[2];

            // 判断是否需要交换
            if ($first < $second) {
                return "$second:$first";
            }
        }

        return $ratio;
    }
    public function updateAllInfo()
    {

    }
}

